package task

import (
	"gitee.com/sansaniot/ssiot-core/facade/env"
	"ssdevice/common/cron"
	cDto "ssdevice/common/dto"
	"ssdevice/common/middleware/mqtt"
	"ssdevice/internal/device/models"
	"ssdevice/internal/device/models/query"
	"ssdevice/internal/rule/engine"
	"ssdevice/internal/rule/model"
	"strings"
)

func Start() {
	// 注册方法
	mqtt.RegisterRuleTask(engine.ExecDevDataTask)

	// 查找所有enable规则下，周期触发的处理器
	rule := model.Rule{}
	rule.Orm = env.Db
	rules, _ := rule.FindEnabled()

	processor := &model.Processor{}
	processor.Orm = env.Db

	for _, r := range rules {
		procList, _ := processor.FindScheduledByRuleId(r.Id)

		for _, p := range procList {
			sns := getStatSns(p.RuleId)
			scheduleId := cron.AddCronTask(p.Schedule, func() { engine.ExecScheduleTask(p, sns) }, false)

			p.Orm = env.Db
			_ = p.SaveScheduleId(int(scheduleId))
			env.Log.Infof("add processor %s with schedule id %d (%s) for %d devices", p.Id, scheduleId, p.Schedule, len(sns))
		}
	}
}

func getStatSns(ruleId string) []string {
	// 获得规则信息
	rule := &model.Rule{}
	rule.Orm = env.Db
	_ = rule.GetById(ruleId)
	ruleSns := make([]string, 0)
	if len(rule.DevSn) > 0 {
		ruleSns = strings.Split(rule.DevSn, ",")
	}
	if len(rule.ProductId) > 0 {
		ruleProductIds := strings.Split(rule.ProductId, ",")
		sysDev := models.SysDev{}
		sysDev.Orm = env.Db
		devList := make([]models.SysDev, 0)
		if err := sysDev.FindList(&devList, cDto.MakeCondition(query.SysDevQuery{ProductModelIn: ruleProductIds})); err != nil {
			return ruleSns
		}
		if len(devList) == 0 {
			return ruleSns
		}
		for _, v := range devList {
			ruleSns = append(ruleSns, v.Sn)
		}
	}
	return ruleSns
}
